package com.wfh.mianshi.manager;


import com.obs.services.ObsClient;
import com.obs.services.exception.ObsException;

import com.wfh.mianshi.config.OBSClientConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.InputStream;

import java.util.UUID;

/**
 * Cos 对象存储操作
 *
 * @author wangfenghuan
 * @from 
 */
@Slf4j
@Component
public class ObsManager {

    @Autowired
    private OBSClientConfig obsClientConfig;


    /**
     * 上传文件到华为云OBS
     * @param multipartFile
     * @return
     * @throws IOException
     */
    public String upload(MultipartFile multipartFile) throws IOException {
        // 获取上传的文件的输入流
        InputStream inputStream = multipartFile.getInputStream();
        String fileName;
        // 避免文件覆盖
        String originalFilename = multipartFile.getOriginalFilename();
        fileName = multipartFile.getName()+  UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));

        // 创建ObsClient实例
        ObsClient obsClient = new ObsClient(obsClientConfig.getAccessKeyId(), obsClientConfig.getSecretAccessKey(), obsClientConfig.getEndpoint());

        try {
            // 上传文件到 OBS
            obsClient.putObject(obsClientConfig.getBucketName(), fileName, inputStream);

            // 文件访问路径
            String url = "https://" + obsClientConfig.getBucketName() + "." + obsClientConfig.getEndpoint() + "/" + fileName;
            // 把上传到OBS的路径返回
            return url;
        } catch (ObsException e) {
            // 处理异常
            throw new RuntimeException("上传文件失败: " + e.getMessage(), e);
        } finally {
            // 关闭obsClient
            if (obsClient != null) {
                try {
                    obsClient.close();
                } catch (Exception e) {
                    // 忽略关闭时可能产生的异常
                }
            }
        }
    }
}
